package com.meitianhui.convenitenbuy.http;

import com.meitianhui.convenitenbuy.BuildConfig;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.http.interceptor.CacheInterceptor;
import com.meitianhui.convenitenbuy.http.interceptor.SignatureInterceptor;
import com.meitianhui.convenitenbuy.http.interceptor.UserAgentInterceptor;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Retrofit Helper.
 * Created by Administrator on 2017/10/23.
 */

public class RetrofitHelper {

    private static final int TIME = 10;
    private static OkHttpClient okHttpClient = null;

    public static <T> T createApi(Class<T> clazz, boolean needSignature, int securityType) {
        return createApi(clazz, needSignature, securityType, Constants.HOST);
    }

    public static <T> T createApi(Class<T> clazz) {
        return createApi(clazz, false, 0, Constants.FILE_HOST);
    }

    public static <T> T createApi(Class<T> clazz, boolean needSignature, int securityType, String url) {
        initOkHttp(needSignature, securityType);
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .client(okHttpClient)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        return retrofit.create(clazz);
    }

    private static void initOkHttp(boolean needSignature, int securityType) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        SignatureInterceptor signInterceptor = new SignatureInterceptor(securityType);
        CacheInterceptor cacheInterceptor = new CacheInterceptor();
        if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
            // builder.addInterceptor(loggingInterceptor);
        }
        //SSL证书
        // builder.sslSocketFactory(TrustManager.getUnsafeOkHttpClient());
        // builder.hostnameVerifier(new TrustManager.TrustAllHostnameVerifier());
        //设置Cache
        // builder.addNetworkInterceptor(cacheInterceptor);//缓存
        // builder.cache(HttpCache.getCache());

        // 判断参数是否需要加密
        if (needSignature) {
            builder.addInterceptor(signInterceptor);
        }
        // 添加 User-Agent
        builder.addInterceptor(new UserAgentInterceptor());

        // 设置超时
        builder.connectTimeout(TIME, TimeUnit.SECONDS);
        builder.readTimeout(TIME, TimeUnit.SECONDS);
        builder.writeTimeout(TIME, TimeUnit.SECONDS);
        // 错误重连
        builder.retryOnConnectionFailure(true);
        okHttpClient = builder.build();
    }

}
